package com.freemalll.merchant.service.impl.coopManagement;


import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freemalll.common.core.exception.BusinessException;
import com.freemalll.merchant.domain.dto.coopManagement.AssetContrastQueryDto;
import com.freemalll.merchant.domain.dto.coopManagement.AssetManageDetailEditDto;
import com.freemalll.merchant.domain.dto.coopManagement.AssetManageEditDto;
import com.freemalll.merchant.domain.dto.coopManagement.AssetManagePageDto;
import com.freemalll.merchant.domain.entity.coopManagement.MerAssetManage;
import com.freemalll.merchant.domain.entity.coopManagement.MerAssetManageDetail;
import com.freemalll.merchant.domain.vo.coopManagement.AssetContrastDetailsVo;
import com.freemalll.merchant.domain.vo.coopManagement.AssetManageDetailsVo;
import com.freemalll.merchant.domain.vo.coopManagement.AssetManagePageVo;
import com.freemalll.merchant.mapper.common.CommonMapper;
import com.freemalll.merchant.mapper.coopManagement.MerAssetManagementMapper;
import com.freemalll.merchant.service.coopManagement.MerAssetManageDetailService;
import com.freemalll.merchant.service.coopManagement.MerAssetManageService;
import com.freemalll.merchant.utils.DtoFieldComparatorUtil;
import com.freemalll.merchant.utils.PinyinUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 服务层实现。
 *
 * @author songshixiong
 * @since 2025-04-29
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MerAssetManageServiceImpl extends ServiceImpl<MerAssetManagementMapper, MerAssetManage> implements MerAssetManageService {

    @Resource
    private MerAssetManageDetailService merAssetManageDetailService;
    @Resource
    private CommonMapper commonMapper;

    @Override
    public Page<AssetManagePageVo> pageSearch(AssetManagePageDto dto) {
        Page<AssetManagePageVo> page = baseMapper.pageSearch(dto.page(), dto);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return page;
        }
        for (AssetManagePageVo vo : page.getRecords()) {
            List<AssetManageDetailsVo> list = merAssetManageDetailService.selectDetails(vo.getSourceId());
            vo.setAssetManageDetailsVo(list);
        }
        return page;

    }

    @Override
    public void edit(AssetManageEditDto dto) {
        if (StringUtils.hasText(dto.getSourceId())) {
            //校验是否存在资方名称
            List<MerAssetManage> merAssetManages = baseMapper.selectList(Wrappers.<MerAssetManage>lambdaQuery()
                    .eq(MerAssetManage::getSourceName, dto.getSourceName())
                    .notIn(MerAssetManage::getSourceId, dto.getSourceId())
            );
            if (!CollectionUtils.isEmpty(merAssetManages)) {
                throw BusinessException.businessOther("资方名称已存在,请重新输入");
            }
            //修改
            MerAssetManage merAssetManage = baseMapper.selectById(dto.getSourceId());
            if (Objects.isNull(merAssetManage)) {
                throw BusinessException.businessOther("资方不存在");
            }
            merAssetManage.setSourceName(dto.getSourceName());
            merAssetManage.setSourceNameInitial(PinyinUtil.getPinyinShort(dto.getSourceName()));
            merAssetManage.setSourceNamePinyin(PinyinUtil.convertToPinyin(dto.getSourceName()));
            baseMapper.updateById(merAssetManage);
            //编辑
            merAssetManageDetailService.editBatch(dto.getDetails(), merAssetManage.getSourceId());
        } else {
            //校验是否存在资方名称
            List<MerAssetManage> merAssetManages = baseMapper.selectList(Wrappers.<MerAssetManage>lambdaQuery().eq(MerAssetManage::getSourceName, dto.getSourceName()));
            if (!CollectionUtils.isEmpty(merAssetManages)) {
                throw BusinessException.businessOther("资方名称已存在,请重新输入");
            }
            //新增
            MerAssetManage merAssetManage = Convert.convert(MerAssetManage.class, dto);
            merAssetManage.setSourceNameInitial(PinyinUtil.getPinyinShort(dto.getSourceName()));
            merAssetManage.setSourceNamePinyin(PinyinUtil.convertToPinyin(dto.getSourceName()));
            baseMapper.insert(merAssetManage);
            merAssetManageDetailService.editBatch(dto.getDetails(), merAssetManage.getSourceId());
        }
    }

    @Override
    public AssetManageEditDto findOneById(String id) {
        if (!StringUtils.hasText(id)) {
            throw BusinessException.businessParamsNotExist("参数为空");
        }
        MerAssetManage merAssetManage = baseMapper.selectById(id);
        if (Objects.isNull(merAssetManage)) {
            throw BusinessException.businessOther("资方不存在");
        }
        AssetManageEditDto assetManageEditDto = Convert.convert(AssetManageEditDto.class, merAssetManage);
        List<MerAssetManageDetail> list = merAssetManageDetailService.list(Wrappers.<MerAssetManageDetail>lambdaQuery().eq(MerAssetManageDetail::getSourceId, id));
        if (CollectionUtils.isEmpty(list)) {
            return assetManageEditDto;
        }
        List<AssetManageDetailEditDto> details = list.stream().map(entity -> Convert.convert(AssetManageDetailEditDto.class, entity)).collect(Collectors.toList());
        assetManageEditDto.setDetails(details);
        return assetManageEditDto;
    }

    @Override
    public List<Map<String, Object>> comparisonOfCapital(AssetContrastQueryDto dto) {
        if (CollectionUtils.isEmpty(dto.getContrastScene()) || CollectionUtils.isEmpty(dto.getContrastSourceIds())) {
            throw BusinessException.businessParamsNotExist("当前对比资方/场景为空,请勾选后再次点击确认");
        }
        //查询当前资方
        List<AssetContrastDetailsVo> currentCapital = baseMapper.queryCurrentCapital(dto);
        if (CollectionUtils.isEmpty(currentCapital)) {
            throw BusinessException.businessOther("当前资方信息未查询到");
        }
        //查对比资方
        List<AssetContrastDetailsVo> compareWithTheCapital = baseMapper.queryList(dto);
        if (CollectionUtils.isEmpty(compareWithTheCapital)) {
            throw BusinessException.businessOther("对比资方信息未查询到");
        }
        List<String> contrastScenes = dto.getContrastScene();
        List<AssetContrastDetailsVo> targetSceneVos = new ArrayList<>();
        Map<String, List<AssetContrastDetailsVo>> map = compareWithTheCapital.stream().collect(Collectors.groupingBy(AssetContrastDetailsVo::getSupportingScenarios));
        // 处理当前资本数据：确保每个场景都有对应数据
        String currentSourceId = currentCapital.get(0).getSourceId();
        for (String scene : contrastScenes) {
            // 查找当前场景的资产数据，不存在则创建默认对象
            AssetContrastDetailsVo sceneVo = currentCapital.stream()
                    .filter(vo -> scene.equals(vo.getSupportingScenarios()))
                    .findFirst()
                    .orElseGet(() -> createDefaultVo(currentSourceId, scene));
            targetSceneVos.add(sceneVo);
            //遍历资方，并根据资方获取对应场景数据，不存在则创建默认对象
            dto.getContrastSourceIds().forEach(contrastId -> {
                List<AssetContrastDetailsVo> compareWithTheCapitalScene = map.getOrDefault(scene, new ArrayList<>());
                // 查找对比资本在当前场景的数据，不存在则创建默认对象
                AssetContrastDetailsVo compareVo = compareWithTheCapitalScene.stream()
                        .filter(vo -> contrastId.equals(vo.getSourceId()))
                        .findFirst()
                        .orElseGet(() -> createDefaultVo(contrastId, scene));
                compareVo.setSourceId(contrastId);
                targetSceneVos.add(compareVo);
            });
        }

        //地址转码
        dealWithProvince(targetSceneVos);
        //查看全部
        if (Boolean.FALSE.equals(dto.getOnlyDiff())) {
            return DtoFieldComparatorUtil.convertDTOListToMapList(targetSceneVos);
        }
        //仅看差异
        return DtoFieldComparatorUtil.convertDTOListToMapListDiff(targetSceneVos);
    }

    private void dealWithProvince(List<AssetContrastDetailsVo> currentCapital) {
        currentCapital.forEach(e -> {
            //客户区域限制
            String customerRegionalRestrictions = e.getCustomerRegionalRestrictions();
            if (StringUtils.hasText(customerRegionalRestrictions)) {
                String[] split = customerRegionalRestrictions.split(",");
                if (split.length > 0) {
                    String customerRegionalRestrictionsStr = commonMapper.selectValueByCodeList(split);
                    e.setCustomerRegionalRestrictions(customerRegionalRestrictionsStr);
                }
            }
            //商户区域限制
            String merRegionalRestrictions = e.getMerRegionalRestrictions();
            if (StringUtils.hasText(merRegionalRestrictions)) {
                String[] split = merRegionalRestrictions.split(",");
                if (split.length > 0) {
                    String merRegionalRestrictionsStr = commonMapper.selectValueByCodeList(split);
                    e.setMerRegionalRestrictions(merRegionalRestrictionsStr);
                }
            }
        });
    }

    @Override
    public List<MerAssetManage> listSearch() {
        return baseMapper.selectList(new QueryWrapper<>());
    }


    /**
     * 创建默认的资产对比详情对象
     */
    private AssetContrastDetailsVo createDefaultVo(String sourceId, String scene) {
        AssetContrastDetailsVo defaultVo = new AssetContrastDetailsVo();
        defaultVo.setSourceId(sourceId);
        defaultVo.setSupportingScenarios(scene);
        return defaultVo;
    }

}
